package com.sh.springbootinit.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sh.springbootinit.common.ErrorCode;
import com.sh.springbootinit.exception.BusinessException;
import com.sh.springbootinit.model.entity.Picture;
import com.sh.springbootinit.service.PictureService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: sh
 * @Date: 2025/1/9 21:45
 * @Description:
 */
@Service
public class PictureServiceImpl implements PictureService {


    @Override
    public Page<Picture> searchPicture(String searchText, long pageNum, long pageSize) {
        long current = (pageNum - 1) * pageSize;
        String url = "https://cn.bing.com/images/search?q="+searchText+"&first="+current;
        Document document = null;
        try {
            document = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "该地址图片搜索失败");
        }
        Elements imageClass = document.getElementsByClass("imgpt");
        List<Picture> pictures = new ArrayList<>();
        for (Element aClass : imageClass) {
            Elements imgTags = aClass.select("a");
            String m = imgTags.attr("m");
            JSONObject jsonObject = new JSONObject(m);
            String imageUrl = (String) jsonObject.get("turl");   //图片地址
            String t = (String) jsonObject.get("t");  // 图片标题
            Picture picture = new Picture();
            picture.setUrl(imageUrl);
            picture.setTitle(t);
            pictures.add(picture);
            if (pictures.size() == pageSize) {
                break;
            }
        }
        Page<Picture> picturePage = new Page<>(pageNum, pageSize);
        picturePage.setRecords(pictures);
        return picturePage;
    }

}

